/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BANewsViewController.m
//  redia-bapps-ios
//
//  Created by Nikolaj Tørring on 10/18/13.
//  Copyright (c) 2013 redia. All rights reserved.
//

#import "BANewsViewController.h"
#import "InfoGalleriImageUrlUtils.h"
#import "LazyLoadManager.h"
#import "WebTextLength.h"
#import "BALibrarySettings.h"
#import "UIColor+HTML.h"
#import "BAWebBrowserViewController.h"
#import "BANewsRelatedsButtonViewController.h"

@interface BANewsViewController (){
    CGFloat imageHeight;
    CGFloat maxImageHeight;
    
    BANewsRelatedsButtonViewController* relatedMaterialsButtonViewController;
    
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *headlineLabel;
@property (weak, nonatomic) IBOutlet UIWebView *bodyWebView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToBottomOfImageConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bodyWebViewHeight;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeightConstraint;

@end

@implementation BANewsViewController

+(BANewsViewController *)newsViewControlerWithNews:(BANews *)news{
    BANewsViewController* newsViewController;
    if (RD_IS_IPAD) {
        newsViewController = [[BANewsViewController alloc] initWithNibName:@"BANewsViewController_iPad" bundle:nil];
    } else{
        newsViewController = [[BANewsViewController alloc] initWithNibName:@"BANewsViewController_iPhone" bundle:nil];
    }
    [newsViewController setNews:news];
    return newsViewController;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    BA_LABEL_SET_FONT_MEDIUM(self.headlineLabel);
    
    imageHeight = self.topToBottomOfImageConstraint.constant;
    
    RD_SET_EDGES_FOR_EXTENDED_LAYOUT_IOS7
    
    relatedMaterialsButtonViewController = [BANewsRelatedsButtonViewController new];
    [self.bottomView addSubview:relatedMaterialsButtonViewController.view];
    [BAUtils setViewToFillParent:relatedMaterialsButtonViewController.view];
    [self addChildViewController:relatedMaterialsButtonViewController];
    
    
    [self.bodyWebView setBackgroundColor:[UIColor clearColor]];
    //id scrollView = [self.bodyWebView.subviews objectAtIndex:0];
    for (UIView * subview in [self.bodyWebView.scrollView subviews]) {
        if([subview isKindOfClass:[UIImageView class]])
            subview.hidden = YES;
    }
    [self.bodyWebView.scrollView setScrollEnabled:NO];
    
    self.scrollView.alwaysBounceVertical = YES;
    [self setupView];
}

-(void)dealloc{
    [[LazyLoadManager instance] cancelConnectionsForOwner:self];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setupView{
    self.bottomViewHeightConstraint.constant = 0;
    
    if (self.isViewLoaded && self.news != nil) {
        [self.headlineLabel setText:self.news.headline];
 
        relatedMaterialsButtonViewController.relatedMaterials = _news.relatedResources;

        /*
        NSMutableString* bodyHtml = [NSMutableString new];
        [bodyHtml appendString:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BANewsEventsBodyTemplate" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil]];
        [bodyHtml appendString:self.news.body];
        [bodyHtml appendString:@"<div id=\"end\"></div></body></html>"];
         */
        
        NSString* bodytemplate = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BANewsEventsBodyTemplate" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
        if (bodytemplate==nil) {
            return;
        }
        NSMutableString* bodyHtml = [bodytemplate mutableCopy];// = [[NSString stringWithFormat:bodytemplate, [[[BALibrarySettings instance] getCustomerColorNormal] toHTMLColorString]] mutableCopy];
        [bodyHtml replaceOccurrencesOfString:@"%1$@"
                                  withString:[[[BALibrarySettings instance] getCustomerColorNormal] toHTMLColorString]
                                     options:0
                                       range:NSMakeRange(0, [bodyHtml length])];
        
        if ([self.news.subHeadline length]>0) {
            [bodyHtml appendFormat:@"<p><em>%@</em></p>",self.news.subHeadline];
        }
        
        [bodyHtml appendString:self.news.body];
        [bodyHtml appendString:@"<br /><div id=\"end\"></div></body></html>"];
        
        [self.bodyWebView loadHTMLString:bodyHtml baseURL:nil];
        
        
//        NSMutableAttributedString* body =[NSMutableAttributedString new];
//        [body appendAttributedString:[NSAttributedString attributedStringWithHTML:self.news.body]];
//        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
//        [style setLineSpacing:5];
//        [body addAttribute:NSParagraphStyleAttributeName
//                          value:style
//                          range:NSMakeRange(0, [body length])];
//        [self.bodyLabel setAttributedText:body];
        
        if ([self.news.imageUrl length]>0) {
            NSString* resizeUrl;
            if (RD_IS_IPAD) {
                resizeUrl = [InfoGalleriImageUrlUtils getResizedImageUrl:self.news.imageUrl toWidth:683 toHeight:2000 usingQuality:7 withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX outputFormat:@"jpeg" doubleUpForRetina:YES]; // ?
            } else{
                resizeUrl = [InfoGalleriImageUrlUtils getResizedImageUrl:self.news.imageUrl toWidth:320 toHeight:1000 usingQuality:7 withMode:IMAGE_URL_UTILS_RESIZE_MODE_BOUNDING_BOX outputFormat:@"jpeg" doubleUpForRetina:YES];
            }
            
            [[LazyLoadManager instance] lazyLoadUIImageFromUrl:resizeUrl withOwner:self setScaleforRetina:YES onSuccess:^(UIImage *image) {
                [self.imageView setImage:[UIImage imageWithCGImage:image.CGImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
                [UIView animateWithDuration:0.25 animations:^{
                    [self.imageView setAlpha:1];
                } completion:^(BOOL finished) {
                    [self.loadingIndicator stopAnimating];
                }];
            } onError:^(LazyLoaderErrorCode errorCode, NSString *errorMessage) {
                [self.loadingIndicator stopAnimating];
            }];

        } else {
            [self.loadingIndicator stopAnimating];
        }
        
        if ([self.news.relatedResources count]>0) {
            self.bottomViewHeightConstraint.constant = 46;
            
        }
        
    }
}

-(void)setNews:(BANews *)news{
    if (_news != news) {
        _news = news;
        
        /* test subheadline
        _news.subHeadline = @"Lorem ipsum dolor sit amelgamium. Underoverskriften skal vel vises under den vandrette streg, men med et andet skriftsnit end brødteksten?";
         */

        /* test identifiers
        _news.relatedResources = @[@"28838166",@"26922143",@"26962579",@"27085806",@"29052298",@"27268188",@"27268161",@"27268145",@"27268129",@"28028644",@"26452910",
                                   @"26595932",@"27085830",@"29052271",@"28837747",@"27223184",@"43913522",@"27223001",@"27223222",@"27223249",@"25510992",@"27925324",
                                   @"26934656",@"251008366b",@"251010880b",@"34064555",@"27006051",@"28075480",@"44829851",@"24633594",@"26370574",@"24025578",
                                   @"27013341",@"07024290",@"05175062",@"23555085",@"28535228",@"28527780",@"23473720",@"07247095",@"21894575",@"06492983"];
         */
        
        [self setupView];
    }
}

#pragma mark UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset = scrollView.contentOffset.y;
    
    self.topToBottomOfImageConstraint.constant = imageHeight-yOffset;
    
}
#pragma mark UIWebViewDelegate


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    if (webView == self.bodyWebView) {
        float height = [WebTextLength measureWebBoxHeight:webView forMarker:@"end"];
        self.bodyWebViewHeight.constant = height;
    }
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        [webView setAlpha:1];
    } completion:nil];
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{

    if (navigationType == UIWebViewNavigationTypeOther) {
        return YES;
    } else {
        NSString* absoluteRequestString = [request.URL absoluteString];
        if ([absoluteRequestString hasPrefix:@"http://"] || [absoluteRequestString hasPrefix:@"https://"]) {
            BAWebBrowserViewController* webBrowserViewControler = [[BAWebBrowserViewController alloc] initWithNibName:@"BAWebBrowserViewController" bundle:nil];
            [webBrowserViewControler setUrl:absoluteRequestString];
            [self presentViewController:webBrowserViewControler animated:YES completion:nil];
            
        } else if ([absoluteRequestString hasPrefix:@"mailto:"]) {
            [[UIApplication sharedApplication] openURL:request.URL];
        }
        return NO;
    }
}


@end
